/******************************************************************************
MSP430g2553 Generic I2C slave

This code does two things:
1)	Blinks an LED on P1.0 on and off with a period of 1 second

2)	Listens as an I2C slave on the address set in I2C_OWN_ADDR.  
	On writes, will store the first byte of data for later use, ignoring reg #
	On reads, will respond with the value (previous write # * register # read)

Based (very loosely) on code written during 
Fall 2011 in ME 461 taught by S. R. Platt
*******************************************************************************/

#include "msp430g2553.h"
#include "i2c_slave.h"
#include "heartbeat.h"
#include "util.h"

#define	I2C_OWN_ADDR	0x20		// address 0x40 -> we receive from master, 0x41 -> we write byte to I2C bus

unsigned char	i2cdata = 0x00;	// scratch pad for playing with i2c info

void main(void) {
	
	// stop the watchdog timer
	WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
	
	// set up internal clocking
	if (CALBC1_16MHZ ==0xFF || CALDCO_16MHZ == 0xFF) while(1);	// set up to use internal oscillator                                             
	DCOCTL = CALDCO_16MHZ;                		// Set uC to run at approximately 16 Mhz
	BCSCTL1 = CALBC1_16MHZ; 
	
	
	// Timer A1 config - PWM
	
	init_heartbeat(10000);	// 1 sec period
	init_i2c_slave(I2C_OWN_ADDR);		

	_BIS_SR(GIE); 						   // Enable global interrupt

	
	while(1) {  
	}  // while
} // main()




void	RX_callback(unsigned char reg, unsigned char* data, short int data_len)
{
	// for testing - ignore register, just store first byte of data as multiplier
	i2cdata = data[0];
}

short int	TX_callback(unsigned char reg, unsigned char* data)
{
	short int data_len = 0;
	
	// return i2cdata * register address
	data_len = 1;
	data[0] = reg * i2cdata;
	
	return data_len;
}
